//
//  GaoImageBrowser.m
//  DuTe
//
//  Created by Gikki Ares on 2020/12/24.
//  Copyright © 2020 vgemv. All rights reserved.
//

#import "JsImageBrowserView.h"
#import "JsGeometryManager.h"
#import "JsImageBrowserViewVm.h"
#import "JsButtonLiiOne.h"
#import "JsImageBrowserViewCell.h"
#import "JsBundleManager.h"
#import "JsWebImageManager.h"

@interface JsImageBrowserView()<
UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,
JsButtonLiiOneDelegate,
UIScrollViewDelegate
>

{
	//显示当前序号的标签.
	UILabel * mlb_indexIndicator;
	UICollectionView * mcv;
	JsImageBrowserViewVm * mvm;
	JsButtonLiiOne * mgaoButton_download;
	JsButtonLiiOne * mgaoButton_close;
	
//	NSArray * marr_image;
	NSArray * marr_model;
	int mi_pageNum;
}

@end

const static int ViewTag_Close = 1;
const static int ViewTag_Download = 2;

@implementation JsImageBrowserView

- (instancetype)init {
	if(self = [super init]) {
		[self commonInit];
	}
	return self;
}

- (void)commonInit {
	self.frame = [self screenBounds];
	mvm = [JsImageBrowserViewVm defaultInstance];
	
	UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
	//如果是数值方向,会有一个inset.
	flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
	mcv = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:flowLayout];
	[self addSubview:mcv];
	mcv.delegate = self;
	mcv.dataSource = self;
	mcv.contentOffset = CGPointMake(0, 0);
	mcv.backgroundColor = [UIColor whiteColor];
	//cv自己默认有一个offset,是这个属性影响的.
	if (@available(iOS 13.0, *)) {
		mcv.automaticallyAdjustsScrollIndicatorInsets = NO;
	} else {
			// Fallback on earlier versions
	}
	mcv.pagingEnabled = YES;
	
	[mcv registerClass:[JsImageBrowserViewCell class] forCellWithReuseIdentifier:@"cell"];
	
	
	mlb_indexIndicator = [UILabel new];
	mlb_indexIndicator.text = @"";
	mlb_indexIndicator.textColor = [UIColor whiteColor];
	[self addSubview:mlb_indexIndicator];
	mlb_indexIndicator.frame = [JsGeometryManager frameHAlignLeftVAlignBottomWithContainerSize:self.bounds.size size:CGSizeMake(mvm.mf_w_indicatorLabel,mvm.mf_h_indicatorLabel) offset:CGPointMake(mvm.leading_indicatorLabel, mvm.bottom_indicatorLabel)];
	{
	mgaoButton_close = [[JsButtonLiiOne alloc]initWithFrame:[JsImageBrowserViewVm closeBtnFrame]];
	[self addSubview:mgaoButton_close];
	mgaoButton_close.tag = ViewTag_Close;
	UIImage * image_close = [JsBundleManager iconInBundleNamed:@"Close_White"];
	[mgaoButton_close setImage:image_close];
	JsButtonLiiVm * vm_close = [mgaoButton_close vm];
	vm_close.btnFrame = mgaoButton_close.bounds;
	[mgaoButton_close setupUi];
	mgaoButton_close.delegate = self;
	}
	
	{
	mgaoButton_download = [[JsButtonLiiOne alloc]initWithFrame:CGRectMake(0, 0, mvm.mf_w_downloadBtn, mvm.mf_h_downloadBtn)];
	mgaoButton_download.tag = ViewTag_Download;
	[self addSubview:mgaoButton_download];
	[mgaoButton_download absolutePositonAtRightBottomWithOffset:CGPointMake(mvm.trailing_downloadBtn, mvm.bottom_downloadBtn)];
	UIImage * image_download = [JsBundleManager iconInBundleNamed:@"Download_White"];
	[mgaoButton_download setImage:image_download];
	[mgaoButton_download setupUi];
	mgaoButton_download.delegate = self;
	
	}
	
	
}

- (void)layoutSubviews {
	[super layoutSubviews];
	
		//lb放在左下角
	[mlb_indexIndicator absolutePositonAtLeftBottomWithOffset:CGPointMake(mvm.leading_indicatorLabel, mvm.bottom_indicatorLabel) size:CGSizeMake(mvm.mf_w_indicatorLabel, mvm.mf_h_indicatorLabel)];
	
	mcv.contentOffset = CGPointMake(0, 0);
	
}



#pragma mark 3 Interface
- (void)setPageNum:(int)pageNum {
	mi_pageNum = pageNum;
	mlb_indexIndicator.text = [NSString stringWithFormat:@"%d/%d",mi_pageNum,(int)marr_model.count];
}

//添加到view.window上去.
- (void)displayImageArr:(NSArray <NSString *> *)arr withFrameArray:(NSArray *)frameArray fromView:(UIView *)view index:(int)index {
	if(index>arr.count-1||index<0) {
		index = 0;
	}
	NSMutableArray * marr = [NSMutableArray array];
	[arr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
		JsImageBrowserViewCellModel * model = [JsImageBrowserViewCellModel new];
		model.mstr_thumbImageUrl = obj;
		model.mstr_originImageUrl = obj;
		model.mrc_initialImageViewFrame = [frameArray[idx] CGRectValue];
		[marr addObject:model];
	}];
	marr_model = marr;
	[self setPageNum:index+1];
	[view.window addSubview:self];
	[mcv reloadData];
	
	//加两个dispactch才会有效.
	dispatch_async(dispatch_get_main_queue(), ^{
	dispatch_async(dispatch_get_main_queue(), ^{
		NSIndexPath * indexPath = [NSIndexPath indexPathForItem:index inSection:0];
		[self->mcv scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
	});
	});
}

#pragma mark 4 Delegate
#pragma mark 4.1 UICollectionDelegate UICollectionViewDatasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	int count = (int)marr_model.count;
	return count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	JsImageBrowserViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
	JsImageBrowserViewCellModel * model = marr_model[indexPath.row];
	[cell setModel:model];
	return cell;
}

#pragma mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
	CGSize size = self.bounds.size;
//	NSLog(@"Cell size is %@",NSStringFromCGSize(size));
	return size;
}

//默认有一个top=20的inset
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
	return UIEdgeInsetsMake(0, 0, 0, 0);
}

//平行滚动方向
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
	return 0;
}

//垂直方向
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
	return 0;
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	//计算当前的PageNum,1 based.
	CGFloat x = scrollView.contentOffset.x;
	CGFloat pageNum = (x+ self.bounds.size.width/2) /self.bounds.size.width + 1;
	[self setPageNum:pageNum];
}

#pragma mark 5 Event
- (void)jsButtonLiiOneClicked:(JsButtonLiiOne *)button {
	switch (button.tag) {
		case ViewTag_Close: {
			[self removeFromSuperview];
			break;
		}
		case ViewTag_Download:{
			JsImageBrowserViewCellModel * model = marr_model[mi_pageNum];
			UIImage * image = [JsWebImageMemoryCache valueForKey:model.mstr_originImageUrl];
			if(image) {
				//存到相册
				
			}
			else {
				[JsWebImageManager downloadImageWithUrlString:model.mstr_originImageUrl completionHandler:^(UIImage * _Nonnull image) {
					if(image) {
						//存到相册
					}
					else {
						//图片获取失败
					}
				}];
			}
			
			break;
		}
	}
}

@end
